from rest_framework import viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from pingtuan import models
from pingtuan.models import Users, Tasks
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin

# # Create your viewss here.
# # class LoginView(APIView):
# #     def post(self,request,*args,**kwargs):
# #         print(request.data)
# #         user = request.data.get('username')
# #         pwd = request.data.get('password')
# #         phone = request.data.get('phone')
# #         user_object = models.Users.objects.filter(username=user,password=pwd,phone=phone).first()
# #         if not user_object:
# #             return Response({'code':1000,'error':'用户名、密码或电话错误'})
# #         random_string = str(uuid.uuid4())
# #         user_object.token = random_string
# #         user_object.save()  # 把随机字符串保存在数据库
# #         return Response({'code':1001,'data':random_string})  # 将token给用户
# # class OrderView(APIView):
# #     def get(self,request,*args,**kwargs):
# #         token = request.query_params.get('token')
# #         if not token:
# #             return Response({'code':2000,'error':'登录成功后才能访问'})
# #         user_obj =models.Users.objects.filter(token = token).first()
# #         if not user_obj:
# #             return Response({'code':2001,'error':'token无效'})
# #         return Response("订单列表")
# # # def index(request):
# # #     mod = models.Users.objects.get(id=2)
# # #     mod.token = str(uuid.uuid4())
# # #     mod.save()
# #
# #
# #     # return HttpResponse('新增数据')
# # class JwtLoginView(APIView):
# #     '''基于JWT用户登录'''
# #
# #     def post(self, request, *args, **kwargs):
# #         print(request.data)
# #         user = request.data.get('username')
# #         pwd = request.data.get('password')
# #         phone = request.data.get('phone')
# #         user_object = models.Users.objects.filter(username=user, password=pwd, phone=phone).first()
# #         if not user_object:
# #             return Response({'code': 1000, 'error': '用户名、密码或电话错误'})
# #
# #         # jwt功能
# #         import jwt
# #         import datetime
# #         salt = 'sdfojhhfis[ofjseodsf'
# #         # Header
# #         headers = {
# #             "typ":'jwt',
# #             'alg':'HS256'
# #         }
# #         #payload
# #         payload = {
# #             'id':user_object.id,
# #             'username':user_object.username,
# #             "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=5) #超时时间
# #         }
# #         token = jwt.encode(payload = payload,key=salt,algorithm='HS256',headers=headers)
# #
# #         return Response({'code': 1001, 'data': token})  # 将token给用户
# #
# #
from pingtuan.extensions.auth import JwtQueryParamsAuthentication
from pingtuan.utils.jwt_auth import create_token
from pingtuan.serializer import UsersSerializer,UserConSerializer


#
#
# class UsersViewSet(viewsets.ModelViewSet):
#     queryset = Users.objects.all()
#     serializer_class = UsersSerializer
#
#
# class TasksViewSet(viewsets.ModelViewSet):
#     queryset = Users.objects.all()
#     serializer_class = TasksSerializer
#
# # class ProLoginView(APIView):
# #     '''基于JWT用户登录'''
# #     authentication_classes = []  #登录页面不用校验
# #     def post(self, request, *args, **kwargs):
# #         print(request.data)
# #         user = request.data.get('username')
# #         pwd = request.data.get('password')
# #         phone = request.data.get('phone')
# #         user_object = models.Users.objects.filter(username=user, password=pwd, phone=phone).first()
# #         if not user_object:
# #             return Response({'code': 1000, 'error': '用户名、密码或电话错误'})
# #         token = create_token({"id":user_object.id, "name":user_object.username},5) # 五分钟时间
# #         return Response({'code': 1001, 'token': token})  # 将token给用户
#
# class TestView(APIView):
#     def get(self, request, *args, **kwargs):
#         print(request.user)
#         return Response('token校验成功，该用户已登录，可以进行操作')
#
#
# class UserAPI(APIView):
#     authentication_classes = []  # 登录注册页面不用校验
#
#     def post(self, request,):
#         # query_params=GET
#         # print(request.data)
#         action = request.data.get('action')
#         print(action)
#         if action == 'register':
#             return self.do_register(request)
#         elif action == 'login':
#             return self.do_login(request)
#
#     def do_register(self, request):
#         serializer = UsersSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data)
#         return Response(serializer.error_messages)
#
#     def do_login(self, request):
#         # print(type(request.data))
#         # print(request.data)
#         phone = request.data.get('phone')
#         password = request.data.get('password')
#         # print(type(password))
#         # print(password)
#
#         try:
#             user_object = models.Users.objects.filter(phone =phone).first()
#             # print(user_object.password)
#             # print("7")
#         except Exception as e:
#             return Response({'msg': '用户不存在，请先注册'})
#
#         if not password == user_object.password:
#             return Response({'msg': 'password error!'})
#
#         token = create_token({"id": user_object.id, "name": user_object.username}, 5)  # 五分钟时间
#
#         data = {
#             'msg': 'login success!',
#             'status': status.HTTP_200_OK,
#             'token': token,
#         }
#         return Response(data)
#
#
# # 实现列表视图
class UsersGenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    # 1. 提供公共属性
    queryset = Users.objects.all()
    serializer_class = UsersSerializer

    def get(self, request):
        '''获取所有的书籍'''
        return self.list(request)

    def post(self, request):
        return self.create(request)


#
#
# class UsersDetailMixinGenericAPIView(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin):
#     # 1. 提供公共属性
#     queryset = Users.objects.all()
#     serializer_class = UsersSerializer
#     lookup_field = 'id'
#
#     def get(self,request,id):
#         return self.retrieve(request)
#
#     def put(self,request,id):
#         return self.update(request)
#
#     def delete(self,request,id):
#         return self.destroy(request)
#
# class TasksGenericAPIView(GenericAPIView,RetrieveModelMixin,ListModelMixin,CreateModelMixin):
#
#     #1. 提供公共属性
#     queryset = Tasks.objects.all()
#     serializer_class = TasksSerializer
#     def get(self,request,pk):
#         '''获取所有的书籍'''
#         # return self.list(request)
#
#         return self.retrieve(request)
#
#     def post(self,request):
#         return self.create(request)
#
#
# class TasksDetailMixinGenericAPIView(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin):
#     # 1. 提供公共属性
#     queryset = Tasks.objects.all()
#     serializer_class = TasksSerializer
#     lookup_field = 'id'
#
#     def get(self,request,id):
#         return self.retrieve(request)
#
#     def put(self,request,id):
#         return self.update(request)
#
#     def delete(self,request,id):
#         return self.destroy(request)

class User(GenericAPIView, CreateModelMixin, RetrieveModelMixin, ):
    """
    用户接口，用于登录/注册
    """
    authentication_classes = []  # 登录注册页面不用校验
    queryset = Users.objects.all()
    serializer_class = UsersSerializer

    def post(self, request):
        phone = request.data.get('phone')
        password = request.data.get('password')
        id = request.data.get('id')
        avatar_url = request.data.get('avatar_url')
        username = request.data.get('username')
        print(phone, password)
        user_object = models.Users.objects.filter(id=id).first()
        print(user_object)
        if user_object == None:
            return self.create(request)
            user_object = models.Users.objects.filter(id=id).first()
        if not phone == user_object.phone:
            return Response({'msg': 'phone error!'})
        if not password == user_object.password:
            return Response({'msg': 'password error!'})
        token = create_token({"id": user_object.id, "name": user_object.phone}, 3000)  # 五分钟时间
        user_object.token = token
        user_object.avatar_url = avatar_url
        user_object.username = username
        user_object.save()
        return Response({'concern_num': user_object.concern_num,
                         "avatar_url": user_object.avatar_url,
                         'fans_num': user_object.fans_num,
                         'token': user_object.token,
                         'username': user_object.username})
    # def register(self,request):
    #     self.create(request, status='register')  # 若不存在openid就注册创建一个


from decimal import Decimal


class Userinfo(GenericAPIView):
    """
    用户信息接口，
    get 查看用户信息 并且热度+0.1
    put 修改用户个人资料
    """
    queryset = Users.objects.all()
    serializer_class = UsersSerializer

    def get(self, request):
        """
        根据token，查询用户资料 增加热度
        可以不传json，只需要url之后？token=即可
        :param request:
        :return:
        """
        token = request.data.get('token')
        # 2. 创建序列化器对象 转换数据
        user = models.Users.objects.get(token=token)
        print(user.hot)
        # print(Decimal('0.1'))
        user.hot += Decimal('0.1')
        print(user.hot)
        user.save()
        # # TODO 序列化改进
        serializer = UsersSerializer(instance=user, data={'hot': user.hot}, partial=True)

        # 3. 校验入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 4.返回响应
        return Response(serializer.data, status=status.HTTP_200_OK)

    def put(self, request):
        """
        修改用户个人资料
        :param request:
        :return:
        """
        token = request._request.GET.get('token')
        # 2. 创建序列化器对象 转换数据
        user = models.Users.objects.get(token=token)
        serializer = self.get_serializer(data=request.data, instance=user, partial=True)
        # 3.校验、数据入库
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 4.返回响应
        return Response(serializer.data, status=status.HTTP_200_OK)  # jsonresponse原则上只接受字典类型

class Usercon(GenericAPIView):
    queryset = Users.objects.all()
    serializer_class = UsersSerializer

    def get(self, request):
        """
        GET请求获取关注的所有人，返回token，名字，标签
        """

        token = request._request.GET.get('token')
        # 2. 创建序列化器对象 转换数据
        user = models.Users.objects.get(token=token)
        print(user.id)
        usercon = models.UserConnection.objects.filter(userid=user.id)
        concern_list = []
        for u in usercon:
            print(u)
            if u.concern_id is None:
                continue
            else:
                concern_user = models.Users.objects.get(id=u.concern_id) #获取关注人的信息
                concern_dict = {
                            "token":concern_user.token,
                            "昵称":concern_user.username,
                            "标签":concern_user.tag,
                        }
                concern_list.append(concern_dict)
        # serializer = UserConSerializer(instance=usercon,many=True)
        #         # print(serializer.data)
        # 4.返回响应
        return Response(concern_list, status=status.HTTP_200_OK)

class Userfan(GenericAPIView):
    queryset = Users.objects.all()
    serializer_class = UsersSerializer

    def get(self, request):
        """
        GET请求获取自己的所有粉丝，返回token，名字，标签
        """

        token = request._request.GET.get('token')
        # 2. 创建序列化器对象 转换数据
        user = models.Users.objects.get(token=token)
        # print(user.id)
        userfan = models.UserConnection.objects.filter(userid=user.id)
        fans_list = []
        # 遍历每一个粉丝
        for u in userfan:
            print(u)
            if u.fans_id is None:
                continue
            else:
                fans_user = models.Users.objects.get(id=u.fans_id) #获取关注人的信息
                fans_dict = {
                            "token":fans_user.token,
                            "昵称":fans_user.username,
                            "标签":fans_user.tag,
                        }
                fans_list.append(fans_dict)

        # 4.返回响应
        return Response(fans_list, status=status.HTTP_200_OK)

